﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;

using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Installer;
using DotNetNuke.Services.Installer.Packages;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI;
using DotNetNuke.UI.Modules;
using DotNetNuke.UI.WebControls;
using DotNetNuke.Services.Installer.Writers;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Tabs;

namespace CharityGamesOnline.Modules.Game
{
    public partial class EditExtension : ModuleUserControlBase
    {
        private const string GAME_EDIT_MODULE = "GameEdit.ascx";
        private Control _Control;
        private GamePackageInfo _Package = null;

        private string CultureCode
        {
            get { return LocaleController.Instance.GetCurrentLocale(ModuleContext.PortalId).Code; }
        }

        protected bool IsSuperTab
        {
            get { return (this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab); }
        }
        public string Mode
        {
            get { return Convert.ToString(ModuleContext.Settings["Extensions_Mode"]); }
        }
        protected GamePackageInfo Package
        {
            get
            {
                if (_Package == null)
                {
                    if (PackageID == Null.NullInteger)
                    {
                        _Package = new GamePackageInfo();
                    }
                    else
                    {
                        GameController ctlGame = new GameController();
                        _Package = ctlGame.GetGamePackage(PackageID);
                    }
                }
                return _Package;
            }
        }
        protected IPackageEditor PackageEditor
        {
            get
            {
                if (_Control == null)
                {
                    if (Package != null)
                    {
                        PackageType _PackageType = PackageController.GetPackageType(Package.PackageType);
                        if ((_PackageType != null) && (!string.IsNullOrEmpty(_PackageType.EditorControlSrc)))
                        {
                            _Control = ControlUtilities.LoadControl<Control>(this, _PackageType.EditorControlSrc);
                        }
                    }
                }
                return _Control as IPackageEditor;
            }
        }
        public int PackageID
        {
            get
            {
                int _PackageID = Null.NullInteger;
                if ((Request.QueryString["PackageID"] != null))
                {
                    _PackageID = Int32.Parse(Request.QueryString["PackageID"]);
                }
                return _PackageID;
            }
        }
        protected PropertyEditorMode ViewMode
        {
            get
            {
                PropertyEditorMode _ViewMode = PropertyEditorMode.Edit;
                return _ViewMode;
            }
        }

        private void LoadGameEditModule()
        {
            phEditor.Controls.Clear();
            PortalModuleBase objModule = LoadControl(GAME_EDIT_MODULE) as PortalModuleBase;
            objModule.ModuleConfiguration = ModuleContext.Configuration.Clone();
            objModule.ID = System.IO.Path.GetFileNameWithoutExtension(GAME_EDIT_MODULE);
            phEditor.Controls.Add(objModule);
        }
        private void BindData()
        {
            fldEmail.ValidationExpression = DotNetNuke.Common.Globals.glbEmailRegEx;            
            
            if (ModuleContext.PortalSettings.ActiveTab.IsSuperTab)
            {
                lblTitle.Text = string.Format(Localization.GetString("HostHeading", LocalResourceFile), Package.FriendlyName);
            }
            else
            {
                lblTitle.Text = string.Format(Localization.GetString("AdminHeading", LocalResourceFile), Package.FriendlyName);
            }
            cmdPackage.Visible = IsSuperTab;
            cmdUpdate.Visible = true;// IsSuperTab;
            lblHelp.Text = Localization.GetString("EditModuleHelp", this.LocalResourceFile);
            cmdUpdate.Text = Localization.GetString("cmdUpdateModule", this.LocalResourceFile);

            if (Package != null)
            {
                if (PackageEditor == null || PackageID == Null.NullInteger)
                {
                    dshExtension.Visible = false;
                    dshPackage.Visible = false;
                    tblExtension.Visible = false;
                }
                else
                {
                    //GameEdit objGameEdit = FindControl<GameEdit>(phEditor);
                    //if (!Null.IsNull(objGameEdit) && !Page.IsPostBack)
                    //{
                    //    objGameEdit.BindData(Package.GameID);
                    //}                                        
                }
                ctlExtension.EditMode = ViewMode;
                ctlExtension.DataSource = Package;
                ctlExtension.DataBind();
                if (Mode != "All")
                {
                    fldPackageType.Visible = false;
                }
                //Determine if Package is ready for packaging
                PackageWriterBase Writer = PackageWriterFactory.GetWriter(Package);
                cmdPackage.Visible = Directory.Exists(Path.Combine(DotNetNuke.Common.Globals.ApplicationMapPath, Writer.BasePath));

                cmdDelete.Visible = (!Package.IsSystemPackage) && (PackageController.CanDeletePackage(Package, ModuleContext.PortalSettings));
                ctlAudit.Entity = Package;
            }
        }
        private void UpdatePackage(bool displayMessage)
        {
            GamePackageInfo package = ctlExtension.DataSource as GamePackageInfo;
            if (package != null)
            {
                UpdateData(package.GameID);
                if (ctlExtension.IsValid && ctlExtension.IsDirty)
                {
                    PackageController.UpdatePackage(package);
                    if (displayMessage)
                    {
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PackageUpdated", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
                    }
                }
            }
            
            //GameEdit objGameEdit = FindControl<GameEdit>(phEditor);
            //if (!Null.IsNull(objGameEdit) && !Page.IsPostBack)
            //{
            //    objGameEdit.UpdateData(Package.GameID);
            //}

            //if (PackageEditor != null)
            //{
            //    PackageEditor.UpdatePackage();
            //}
        }
        protected override void OnInit(System.EventArgs e)
        {
            //LoadGameEditModule();
            base.OnInit(e);            
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            cmdCancel.Click += new EventHandler(cmdCancel_Click);
            cmdDelete.Click += new EventHandler(cmdDelete_Click);
            cmdPackage.Click += new EventHandler(cmdPackage_Click);
            cmdUpdate.Click += new EventHandler(cmdUpdate_Click);

            BindData();
            if (!Page.IsPostBack && !Null.IsNull(Package))
            {
                BindGameData(Package.GameID);
            }

        }
        private void Package_Updated(object sender, EventArgs e)
        {
        }
        protected void cmdCancel_Click(object sender, System.EventArgs e)
        {
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
        }
        protected void cmdDelete_Click(object sender, System.EventArgs e)
        {
            Response.Redirect(Util.UnInstallURL(ModuleContext.TabId, PackageID));
        }
        protected void cmdPackage_Click(object sender, System.EventArgs e)
        {
            try
            {
                UpdatePackage(false);
                Response.Redirect(Util.PackageWriterURL(ModuleContext, PackageID));
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
        protected void cmdUpdate_Click(object sender, System.EventArgs e)
        {
            try
            {
                UpdatePackage(true);
                Response.Redirect(Request.RawUrl, true);
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
            }
        }

        #region Game Related Functions

        public void BindGameData(int gameID)
        {
            if (gameID>0)
            {
                GameController ctlGame = new GameController();
                GameInfo objGame = ctlGame.GetGame(gameID);
                if (!Null.IsNull(objGame))
                {
                    pnlGameEdit.Visible = true;
                    lblMessage.Visible = false;
                    txtGameName.Text = objGame.Name;
                    txtDescription.Text = objGame.Description;

                    List<TabInfo> listTabs = TabController.GetPortalTabs(TabController.GetTabsBySortOrder(ModuleContext.PortalId, CultureCode, true), Null.NullInteger, true, "<" + Localization.GetString("None_Specified") + ">", true, false, false, false, false);
                    ddlGameTabID.DataSource = listTabs;
                    ddlGameTabID.DataBind();

                    if (objGame.GameTabID > 0)
                    {
                        ListItem selItem = ddlGameTabID.Items.FindByValue(objGame.GameTabID.ToString());
                        if (selItem != null)
                            selItem.Selected = true;
                    }

                    chkImageDisplay.Checked = objGame.ImageDisplay;
                    ctlImageURL.Url = objGame.ImageURL;
                    ctlImageURL.UrlType = objGame.ImageType;
                    txtImageWidth.Text = objGame.ImageWidth.ToString();
                    txtImageHeight.Text = objGame.ImageHeight.ToString();
                }
                else
                {
                    Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
                    pnlGameEdit.Visible = false;
                    lblMessage.Visible = true;
                    lblMessage.Text = Localization.GetString("ErrorNoData", LocalResourceFile);
                }
            }
        }

        private void UpdateData(int gameID)
        {
            try
            {
                if (gameID>0)
                {
                    GameController ctlGame = new GameController();
                    GameInfo objGame = new GameInfo();
                    objGame.GameID = gameID;
                    objGame.PortalID = ModuleContext.PortalId;
                    objGame.Name = txtGameName.Text;
                    objGame.Description = txtDescription.Text;
                    
                    objGame.ImageURL = ctlImageURL.Url;
                    objGame.ImageType = ctlImageURL.UrlType;
                    if (string.IsNullOrEmpty(txtImageWidth.Text))
                        objGame.ImageWidth = 0;
                    else
                        objGame.ImageWidth = Int32.Parse(txtImageWidth.Text);
                    if (string.IsNullOrEmpty(txtImageHeight.Text))
                        objGame.ImageHeight = 0;
                    else
                        objGame.ImageHeight = Int32.Parse(txtImageHeight.Text);
                    objGame.ImageDisplay = chkImageDisplay.Checked;

                    objGame.GameTabID = Int32.Parse(ddlGameTabID.SelectedValue);

                    ctlGame.SaveGame(objGame);
                }
            }
            catch (Exception exc)
            {
                //Module failed to load 
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        private T FindControl<T>(Control ctlParent)
        {
            T tRet = default(T);
            foreach (Control objCtl in ctlParent.Controls)
            {
                if (objCtl is T)
                {
                    IModuleControl iModule = (IModuleControl)objCtl;
                    tRet = (T)iModule;
                    //tRet = (T)Convert.ChangeType(objCtl, typeof(T));
                    break;
                }
            }
            return tRet;
        }
        #endregion
    }
}